package minijvm.cmd;

import minijvm.clz.ClassFile;
import minijvm.constant.ConstantInfo;
import minijvm.constant.ConstantPool;
import minijvm.constant.StringInfo;
import minijvm.engine.ExecutionResult;
import minijvm.engine.Heap;
import minijvm.engine.JavaObject;
import minijvm.engine.StackFrame;

/**
 * 从位于方法区的运行时常量池中提取数据，压入栈中
 *
 * @author ChangLiang
 * @date 2020/4/26
 */
public class LdcCmd extends OneOperandCmd {

    protected LdcCmd(ClassFile clzFile, String opCode) {
        super(clzFile, opCode);
    }

    @Override
    public void execute(StackFrame frame, ExecutionResult result) {
        ConstantPool pool = this.getPool();
        ConstantInfo info = pool.getConstantInfo(getOperand());
        if (info instanceof StringInfo) {
            StringInfo stringInfo = (StringInfo) info;
            String value = stringInfo.toString();
            JavaObject javaObject = Heap.getInstance().newString(value);
            frame.getOperandStack().push(javaObject);
        } else {
            throw new RuntimeException("Only support StringInfo constant");
        }
    }
}
